package com.example.hospital.api.common.handler;

import com.example.hospital.api.common.Result;
import com.example.hospital.api.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    public Result exceptionHandler(BaseException ex){
        log.error("业务异常信息：{}", ex.getMessage());
        return Result.error(ex.getErrorCode(), ex.getErrorMsg());
    }

    @ExceptionHandler(value = NullPointerException.class)
    public Result exceptionHandler(NullPointerException ex){
        return Result.error(ExceptionEnum.BODY_NOT_MATCH);
    }

    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String msg = ex.getMessage();
        log.error("数据库异常:{}", msg);
        return Result.error(ExceptionEnum.DB_ERROR);
    }

}
